<template>
  <div class="contract-add-wrap">
    <el-form label-position="left" label-width="100px" :model="formdata" :rules="rules" ref="Form">
      <section>
        <h1 class="section-title">客户信息</h1>
        <div class="info-item border-top flex">
          <el-form-item label="甲方名称" style="width: 50%" prop="CompanyName">
            <el-input v-model="formdata.CompanyName" style="width: 250px" placeholder="请填写甲方名称"></el-input>
          </el-form-item>
          <el-form-item label="社会信用码" style="width: 50%" prop="CreditCode">
            <el-input v-model="formdata.CreditCode" style="width: 250px" placeholder="请填写社会信用码"></el-input>
          </el-form-item>
        </div>
        <div class="info-item border-top flex">
          <el-form-item label="公司地址" prop="City" style="width: 50%">
            <area-select 
              hideArea
              :province="formdata.Province" 
              :city="formdata.City" 
              @provinceChange="(e)=>formdata.Province=e" 
              @cityChange="(e)=>formdata.City=e"
              ></area-select>
          </el-form-item>
          <el-form-item label="详细地址" style="width: 50%">
            <el-input v-model="formdata.Address" style="width: 250px" placeholder="请填写详细地址"></el-input>
          </el-form-item>
        </div>
        <div class="info-item border-top flex">
          <el-form-item label="传真" style="width: 50%">
            <el-input v-model="formdata.Fax" style="width: 250px" placeholder="请填写传真"></el-input>
          </el-form-item>
          <el-form-item label="电话" style="width: 50%">
            <el-input v-model="formdata.Phone" style="width: 250px" placeholder="请填写电话"></el-input>
          </el-form-item>
        </div>
        <div class="info-item border-top flex">
          <el-form-item label="邮编" style="width: 50%">
            <el-input v-model="formdata.Postcode" style="width: 250px" placeholder="请填写邮编"></el-input>
          </el-form-item>
        </div>
      </section>

      <section>
        <h1 class="section-title">合同信息</h1>
        <div class="info-item border-top flex">
          <el-form-item label="合同编号" style="width: 50%">
            <span>{{ handleRandomCode() }}</span>
          </el-form-item>
          <el-form-item label="合同归属" style="width: 50%">
            <span>{{ formdata.ProductId === 1 ? 'FICC' : '权益' }}</span>
          </el-form-item>
        </div>
        <div class="info-item border-top">
          <el-form-item label="合同类型" prop="ContractType">
            <el-radio-group v-model="formdata.ContractType">
              <el-radio label="新签合同">新签合同</el-radio>
              <el-radio label="续约合同">续约合同</el-radio>
              <el-radio label="补充协议">补充协议</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="info-item border-top flex">
          <el-form-item label="合同期限" prop="timeRange" style="width: 50%">
            <el-date-picker
              v-model="formdata.timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            >
            </el-date-picker>
          </el-form-item>
          <span style="line-height: 40px">{{ formatTimeRange(formdata.timeRange) }}</span>
        </div>
        <div class="info-item border-top flex">
          <el-form-item label="合同金额" style="width: 50%" prop="OriginalPrice">
            <el-input v-model="formdata.OriginalPrice" style="width: 250px" placeholder="请填写合同金额"></el-input>
          </el-form-item>
          <span style="line-height: 40px">{{ formatPrice(formdata.OriginalPrice) }}</span>
        </div>
        <div class="info-item border-top flex">
          <el-form-item label="优惠后金额" style="width: 50%">
            <el-input v-model="formdata.Price" style="width: 250px" placeholder="请填写优惠后金额"></el-input>
          </el-form-item>
          <span style="line-height: 40px">{{ formatPrice(formdata.Price) }}</span>
        </div>
        <div class="info-item border-top">
          <el-form-item label="付款方式" prop="PayRemark">
            <el-input v-model="formdata.PayRemark" type="textarea" placeholder="请填写付款方式"></el-input>
            <p style="margin: 0px">
              如：甲方自合同生效日起的十日之内一次性支付一年服务费，乙方收款后为甲方开具合法有效的增值税发票。
            </p>
          </el-form-item>
        </div>
        <div class="info-item border-top">
          <el-form-item label="备注" prop="SellerRemark">
            <el-input v-model="formdata.SellerRemark" type="textarea" placeholder="请填写备注"></el-input>
          </el-form-item>
        </div>
      </section>
      
      <section>
        <h1 class="section-title">服务内容</h1>
        <service-table :ProductId="formdata.ProductId" ref="ServiceTable"></service-table>
        <p style="margin-top: 30px; margin-bottom: 20px">补充内容（eg额外赠送、路演次数规定）</p>
        <el-radio-group v-model="formdata.hasRemark">
          <el-radio label="2">无</el-radio>
          <el-radio label="1">有</el-radio>
        </el-radio-group>
        <el-input
          type="textarea"
          v-model="formdata.Remark"
          v-if="formdata.hasRemark === '1'"
          placeholder="请填写补充内容"
          style="margin-top: 20px"
        ></el-input>
        <div style="text-align: center; margin-top: 20px">
          <el-button type="primary" plain @click="handleSubmit('preview')">预览</el-button>
          <el-button type="primary" @click="handleSubmit('save')">存草稿</el-button>
          <el-button type="primary" @click="handleSubmit('submit')">提交</el-button>
        </div>
      </section>
    </el-form>
  </div>
</template>

<script lang="ts">

import { defineComponent, reactive, toRefs, ref, getCurrentInstance } from 'vue'
import ServiceTable from './components/ServiceTable.vue'
import areaSelect from '@/components/AreaSelect.vue'
import { ElMessage } from 'element-plus'
import { timeToYear, priceToChinese } from './util'
import { useStore } from 'vuex'
import {apiContractPreView,apiContractAdd} from '@/api/contract'
import { useRouter } from 'vue-router'
export default defineComponent({
  name: 'AddContract',
  components: {
    ServiceTable,areaSelect
  },
  setup() {
    // const message = getCurrentInstance()?.appContext.config.globalProperties.$message;
    const store = useStore()
    const router=useRouter()

    const Form = ref() //表单
    let form = reactive({
      formdata: {
        ProductId: store.state.user.data.RoleTypeCode === 'ficc_seller' ? 1 : 2,
        ContractType: '',
        timeRange: '',
        OriginalPrice: '',
        Price: '',
        PayRemark: '',
        CompanyName: '',
        CreditCode: '',
        Province: '',
        City: '',
        Address: '',
        Fax: '',
        Phone: '',
        Postcode: '',
        hasRemark: '2',
        Remark: '',
        SellerRemark:''
      },
      rules: {
        ContractType: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
        timeRange: [{ required: true, message: '请选择合同期限', trigger: 'change' }],
        OriginalPrice: [{ required: true, message: '请填写合同金额', trigger: 'blur' }],
        PayRemark: [{ required: true, message: '请填写付款方式', trigger: 'blur' }],
        CompanyName: [{ required: true, message: '请填写甲方名称', trigger: 'blur' }],
        CreditCode: [{ required: true, message: '请填写社会信用码', trigger: 'blur' }],
        City:[{ required: true, message: '请选择地址', trigger: 'change' }]
      }
    })

    //随机生成一个合同编号
    const handleRandomCode = () => {
      const type: string = store.state.user.data.RoleTypeCode === 'ficc_seller' ? 'FICC' : 'EQ'
      const time = new Date()
      let year = time.getFullYear()
      let month = time.getMonth() + 1 < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1
      let day = time.getDate() < 10 ? '0' + time.getDate() : time.getDate()
      let timeStr = `${year}${month}${day}`
      const radomNum = Math.random().toFixed(3).split('.')[1]
      return `HZ${type}${timeStr}${radomNum}`
    }

    // 格式化合同时间期限
    const formatTimeRange = (timeRange: Array<string>): string => {
      if (timeRange) {
        return `有效期为 ${timeToYear(timeRange)} 年`
      }
      return ''
    }

    //格式化金额为大写
    const formatPrice = (price: number): string => {
      if (price) {
        return `大写：${priceToChinese(price)}`
      }
      return ''
    }

    const ServiceTable = ref()
    // 提交 type: preview 预览 save 存草稿 submit 提交
    const handleSubmit = async (type: string) => {
      try {
        await Form.value.validate()
        // 获取选中的套餐
        let list: any = []
        ServiceTable.value.table.forEach((item: any) => {
          let obj = {}
          if (item.selected) {
            obj = {
              Detail: item.Detail,
              ServiceTemplateId: item.ServiceTemplateId,
              Title: item.Title,
              Value: item.Value
            }
            list.push(obj)
          }
        })
        if (list.length === 0) {
          ElMessage({
            message: '请选择套餐',
            type: 'warning'
          })
          return
        }

        let params = {
          ContractType: form.formdata.ContractType,
          StartDate: form.formdata.timeRange[0],
          EndDate: form.formdata.timeRange[1],
          OriginalPrice: Number(form.formdata.OriginalPrice),
          Price: Number(form.formdata.Price),
          PayRemark: form.formdata.PayRemark,
          CompanyName: form.formdata.CompanyName,
          CreditCode: form.formdata.CreditCode,
          Province: form.formdata.Province,
          City: form.formdata.City,
          Address: form.formdata.Address,
          Fax: form.formdata.Fax,
          Phone: form.formdata.Phone,
          Postcode: form.formdata.Postcode,
          Remark: form.formdata.Remark,
          TemplateId: form.formdata.ProductId,
          Service: list,
          IsAudit: type==='submit'?true:false,
          SellerRemark:form.formdata.SellerRemark,
        }

        if(type==='preview'){
          const res=await apiContractPreView(params)
          if(res.Ret===200){
            sessionStorage.setItem("tempContract", res.Data.Html);
            let { href } = router.resolve({ path: "/contract/preview" });
            window.open(href, "_blank");
          }
        }else{
          const res=await apiContractAdd(params)
          if(res.Ret===200){
            ElMessage({
              message: '操作成功',
              type: 'success'
            })
            router.go(-1)
          }
        }

      } catch (error) {
        ElMessage({
          message: '请完善填写内容',
          type: 'warning'
        })
      }
    }

    handleRandomCode()
    return {
      ...toRefs(form),
      Form,
      ServiceTable,
      formatTimeRange,
      formatPrice,
      handleRandomCode,
      handleSubmit
    }
  }
})
</script>

<style lang="scss" scoped>
section {
  background-color: #fff;
  border: 1px solid #aab4cc;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  .border-top {
    border-top: 1px solid#dcdfe6;
  }
  .section-title {
    font-size: 16px;
    margin-top: 0;
    margin-bottom: 20px;
  }
}
.contract-add-wrap {
  .info-item {
    padding-top: 20px;
  }
}
</style>
